<?php

namespace common\models;

use backend\models\PackageInitiationPlan;
use backend\models\ProjectPreEvaluationInterview;
use backend\models\ProjectPreEvaluationOtherValue;
use backend\models\ProjectPreEvaluationSeal;
use backend\models\ProjectPreEvaluationValue;
use Yii;
use yii\db\Exception;
use common\models\ProjectTransfer;
use common\models\ProjectPreEvaluationValueEvaluation;
use common\models\Responses;
use common\models\ProjectPreEvaluationLawsuit;
use backend\models\ProjectTransferHistory;
use yii\helpers\ArrayHelper;
use yii\web\Request;

/**
 * This is the model class for table "project".
 *
 * @property string $id
 * @property string $code
 * @property string $title
 * @property string $package_id
 * @property integer $category
 * @property string $access
 * @property string $access_users
 * @property integer $status
 * @property string $borrower
 * @property integer $province
 * @property integer $city
 * @property string $industry
 * @property string $type
 * @property integer $management_status
 * @property string $principal
 * @property string $interest
 * @property integer $is_highlights
 * @property string $highlights
 * @property integer $is_suit
 * @property string $guarantor
 * @property integer $guarantor_status
 * @property string $warranty
 * @property integer $mortgage_type
 * @property string $created_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 * @property integer $is_finished
 * @property integer $enterprise
 * @property string $type2
 * @property string $mortgage_details
 * @property string $updated_at
 * @property integer $upload_id
 */
class Project extends \yii\db\ActiveRecord
{
    //项目状态
    const STATUS_BASE = 1;
    //const STATUS_INITIATIN = 2;
    const STATUS_APPROVAL = 4;
    //const STATUS_EVALUATION = 3;
    //const STATUS_TRANSFER = 6;
    const STATUS_FOLLOW = 5;

    //经营状态
    const MANAGEMENT_STATUS_EXISTENCE = 1;
    const MANAGEMENT_STATUS_SUPENSION = 2;
    const MANAGEMENT_STATUS_WRITEOFF = 3;
    const MANAGEMENT_STATUS_BANKRUPTCY = 4;
    //const MANAGEMENT_STATUS_MANAGE = 5;
    //const MANAGEMENT_STATUS_OTHER = 6;

    //高亮状态
    const IS_HIGHIGHTS_TRUE = 1;
    const IS_HIGHIGHTS_FALSE = 2;

    //诉讼状态
    const IS_SUIT_FALSE = 0;//未诉
    const IS_SUIT_TRUE = 1;//已诉
    const SECTION_SUIT = 2;//部分诉讼

    private $status_array_title = array(
        self::STATUS_BASE => '无',
        //self::STATUS_INITIATIN => '启动尽调',
        self::STATUS_APPROVAL => '已立项',
        //self::STATUS_EVALUATION => '已评估',
        //self::STATUS_TRANSFER => '已受让',
        self::STATUS_FOLLOW => '立项待跟进'
    );

    private $management_status_array_title = array(
        self::MANAGEMENT_STATUS_BANKRUPTCY => '破产',
        self::MANAGEMENT_STATUS_EXISTENCE => '存续',
        self::MANAGEMENT_STATUS_SUPENSION => '吊销',
        self::MANAGEMENT_STATUS_WRITEOFF => '注销',
        //self::MANAGEMENT_STATUS_MANAGE => '在营',
        //self::MANAGEMENT_STATUS_OTHER => '其它'
    );

    private $is_highlights_array_title = array(
        self::IS_HIGHIGHTS_TRUE => '是',
        self::IS_HIGHIGHTS_FALSE => '否',
    );

    private $is_suit_array_title = array(
        self::IS_SUIT_FALSE => '未诉',
        self::IS_SUIT_TRUE => '已诉',
        self::SECTION_SUIT => '部分诉讼',
    );

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project';
    }

    /*关联资产包表*/
    public function getPackage()
    {
        return $this->hasOne(Package::className(), ['id' => 'package_id']);
    }

    /*关联配置团队表*/
    public function getTeam()
    {
        return $this->hasOne(ProjectTeam::className(), ['project_id' => 'id']);
    }

    /*关联 项目尽调报告-债权基本情况*/
    public function getInvestigation()
    {
        return $this->hasOne(ProjectInvestigation::className(), ['project_id' => 'id']);
    }

    /* 关联表 项目尽调报告-干系人及资产情况*/
    public function getStakeholder()
    {
        return $this->hasMany(ProjectInvestigationStakeholder::className(), ['project_id' => 'id']);
    }

    /*关联表 项目附件（尽调9+1附件）*/
    public function getInvestigationFile()
    {
        return $this->hasMany(ProjectInvestigationFile::className(), ['project_id' => 'id']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
//            [['package_id','title', 'borrower', 'principal', 'interest', 'created_at', 'is_suit'], 'required'],
            //[['code', 'title', 'package_id', 'category', 'access_users', 'status', 'borrower', 'province', 'city', 'industry', 'management_status', 'principal', 'interest', 'highlights', 'guarantor', 'guarantor_status', 'warranty', 'mortgage_type', 'created_at','is_suit'], 'required'],
            [['package_id', 'category', 'status', 'type', 'province', 'city', 'management_status', 'is_highlights', 'lock_user', 'is_suit', 'is_finished', 'enterprise', 'type2', 'upload_id'], 'integer'],
            [['principal', 'interest'], 'number'],
            [['highlights', 'warranty', 'mortgage_type', 'mortgage_details'], 'string'],
            [['created_at', 'updated_at', 'access', 'access_users',], 'safe'],
            [['code', 'title', 'guarantor_status', 'borrower', 'industry', 'principal', 'interest', 'guarantor', 'lock_timestamp'], 'string', 'max' => 255],
        ];
    }

    /*关联省市*/
    public function getProvinceName()
    {
        return $this->hasOne(Country::className(), ['id' => 'province'])->asArray();
    }

    /*关联城市表*/
    public function getCityName()
    {
        return $this->hasOne(Country::className(), ['id' => 'city'])->asArray();
    }

    /*关联表 司法进展 （混合类）(抵押类)（ly）*/
    public function getLawsuit()
    {
        return $this->hasOne(ProjectPreEvaluationLawsuit::className(), ['project_id' => 'id'])->asArray();
    }

    /*关联表 价值评估（混合类）（ly） */
    public function getEvaluation()
    {
        return $this->hasOne(ProjectPreEvaluationValueEvaluation::className(), ['project_id' => 'id'])->asArray();
    }

    /*关联表 补充说明 (混合类)（ly）*/
    public function getNote()
    {
        return $this->hasOne(ProjectPreEvaluationOtherNote::className(), ['project_id' => 'id'])->asArray();
    }

    /*关联表 抵押基本信息 （抵押类）（ly）*/
    public function getMortgage()
    {
        return $this->hasMany(ProjectPreEvaluationMortgage::className(), ['project_id' => 'id']);
    }

    /*关联表  回现评估(抵押类)（ly）*/
    public function getPayment()
    {
        return $this->hasOne(ProjectPaymentCollection::className(), ['project_id' => 'id'])->asArray();
    }

    /*关联表抵押类 oValue project_pre_evaluation_other_value 非抵押评估*/
    public function getOValue()
    {
        return $this->hasOne(ProjectPreEvaluationOtherValue::className(), ['project_id' => 'id']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'code' => '项目编号',
            'title' => '名称',
            'package_id' => '所属资产包',
            'category' => '类型',
            'access' => '访问权限',
            'access_users' => '部分访问的人的ID',
            'status' => '项目状态',
            'borrower' => '借款人',
            'province' => '省份',
            'city' => '城市',
            'industry' => '行业',
            'type' => '显示形式',
            'management_status' => '经营状态',
            'principal' => '本金（元）',
            'interest' => '利息（元）',
            'is_highlights' => '是否亮点',
            'highlights' => '亮点明细',
            'is_suit' => '是否诉讼',
            'guarantor' => '保证人',//（保证、混合类项目）
            'guarantor_status' => '保证人经营状况',
            'warranty' => '担保方式',
            'mortgage_type' => '抵押物类型',//（保证、混合类）
            'created_at' => '创建时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
            'is_finished' => '是否完成',
            'enterprise' => '企业类型',
            'type2' => '类型',
            'mortgage_details' => '抵押物详情描述',
            'updated_at' => '更新时间',
            'upload_id' => '上传excel'
        ];
    }

    /**
     * 项目状态
     *
     * @return array
     */
    public function getStatusTitle()
    {
        return $this->status_array_title;
    }

    /**
     * 经营状态
     *
     * @return array
     */
    public function getManagementStatusTitle()
    {
        return $this->management_status_array_title;
    }

    /**
     * 保证、混合类抵押物类型
     *
     * @return mixed
     */
    public function getMortgageTypeTitel()
    {
        return Yii::$app->params['mortgageType'];
    }

    /**
     * 是否高亮
     *
     * @return array
     */
    public function getIsHighlightsTitle()
    {
        return $this->is_highlights_array_title;
    }

    /**
     * 项目类型
     *
     * @return array
     */
    public function getCategoryArrayTitle()
    {
        // return unserialize(PACKAGE_TYPE);(ly改)
        return Yii::$app->params['package_type'];
    }

    /**
     * 是否诉讼
     *
     * @return array
     */
    public function getIsSuitTitle()
    {
        return $this->is_suit_array_title;
    }

    /**
     * 单项目权限配置
     *
     * @param $id 单项目id
     * @param $userId  用户id
     * @return array
     */
    public function setPermissionForProject($access_users, $access, $id)
    {
        $model = Project::findOne($id);
        $model->id = $id;
        $model->access = $access . "";
        $model->access_users = implode(",", $access_users);
        //$re = $model->update();
        $re = $model->save();

        if ($re) {
            //'总裁办', '风控管理中心', '财务部', '技术部'
            $data = ['not in','department',['ceooffice', 'windControlManagementCenter', 'finance', 'technology']];
            $userModel = new UserModel();
            $list = $userModel->getDepartmentUsersList();
            $userList = $userModel->getList($data);
            $ids = ArrayHelper::getColumn($userList, 'id');

            $tmp_msg = "";
            foreach ($model->getErrors() as $value) {
                $tmp_msg .= $value[0];
            }
            if ($tmp_msg == "") {
//                $projectLog = new ProjectLog();
//                $projectLog->project_id = $model->id;
//                $projectLog->created_at = date('Y-m-d H:i:s');
//                $projectLog->user_id = Yii::$app->user->id;
//                $projectLog->log = "访问权限变更";
//                $re = $projectLog->save();
//                if (!$re) {
//                    throw new Exception('单项目日志保存失败');
//                }

                $projectLog = new ProjectUpdateLog();
                $module_title_array = $projectLog->getModuleArrayTitle();
                $projectLog->project_id = $model->id;
                $projectLog->created_at = date('Y-m-d H:i:s');
                $projectLog->type = Project::findOne($model->id)->type;
                $projectLog->user_id = Yii::$app->user->id;
                $projectLog->module = $module_title_array[ProjectUpdateLog::MODULE_PERMISSION];
                $user_name = array();

                //过滤默认部门人员
                if (!empty($list)) {
                    foreach($access_users as $value){
                        if (in_array($value, $ids)) {
                            array_push($user_name, $list[(int)$value]['realname']);
                        }
                    }
                } else {
                    foreach($access_users as $value){
                        if (in_array($value, $ids)) {
                            array_push($user_name, User::findOne($value)->realname);
                        }
                    }
                }

                $projectLog->log = "权限更改为：" . join('，', $user_name);
                $re = $projectLog->save();
                if (!$re) {
                    throw new Exception('单项目日志保存失败');
                }
                return array('state' => true, 'msg' => '权限更新成功');
            } else {
                return array('state' => false, 'msg' => $tmp_msg);
            }
        }
        return array('state' => true, 'msg' => '权限更新成功');
    }

    //------------------------------------------model功能start-----------von----------------------
    /*
     * 保存单项目的基础信息
     */
    public static function saveBaseData($data)
    {
        $updata_state = false; //是新增还是更新   true为更新
        if (!empty($data['Id'])) {
            $projeactModel = Project::find()->where(['id' => $data['Id']])->one();
            $updata_state = true;
        } else {
            $projeactModel = new Project();
            $projeactModel->package_id = intval($data['package_id']);
        }
        if (empty($projeactModel)) {
            $projeactModel = new Project();
            $projeactModel->package_id = intval($data['package_id']);
        }
        $projeactModel->title = $data['Title'];
//            $projeactModel->code = $data['Code'];
        $projeactModel->type2 = intval($data['Category']);
        $projeactModel->province = intval($data['Province']);
        $projeactModel->city = $data['City'];
        $projeactModel->borrower = $data['borrower'];
        $projeactModel->enterprise = intval($data['enterprise']);
        $projeactModel->industry = $data['industry'];
        $projeactModel->guarantor = $data['guarantor'];
        $projeactModel->guarantor_status = $data['guarantor_status'];
        $projeactModel->mortgage_type = $data['mortgage_type'];
        $projeactModel->principal = $data['principal'];
        $projeactModel->interest = $data['interest'];
        $projeactModel->is_suit = $data['is_suit'];
        $projeactModel->management_status = $data['borrowerState'];
        $projeactModel->highlights = $data['highlights'];
        $projeactModel->warranty = $data['warranty'];
        $projeactModel->mortgage_details = $data['mortgage_details'];
        $transaction = \Yii::$app->db->beginTransaction();
        $updateData = $projeactModel->getDirtyAttributes();

        if ($updata_state) {
            self::setUpdateLog($projeactModel->id, $updateData, Yii::$app->user->id, ProjectUpdateLog::MODULE_BASE, $projeactModel->type, 2);
        }

        try {
            $params['project_id'] = $data['Id'];
            $dataF['borrowerState'] = $data['borrowerState'];
//            $savaState = self::saveProjectInvestigationStakeholder($params, $dataF);
            $projectState = $projeactModel->save(false);

            if ($projectState) {
                if (!$updata_state) {
                    self::setUpdateLog($projeactModel->id, $projeactModel, Yii::$app->user->id, ProjectUpdateLog::MODULE_BASE, $projeactModel->type, 1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
  *  保存/更新借款人状态
  *  @$param $params 条件
  *  @$param $data   数据
  *  @return bool
  */
    public static function saveProjectInvestigationStakeholder($params, $data)
    {
        $project_id = $params['project_id'];
        if (!empty($project_id)) {
            $investigationModel = ProjectInvestigationStakeholder::find()->where(['project_id' => $project_id])->one();
        } else {
            $investigationModel = new ProjectInvestigationStakeholder();
        }
        if (empty($investigationModel)) {
            $investigationModel = new ProjectInvestigationStakeholder();
        }
        if (!empty($params['project_id'])) {
            $investigationModel->project_id = $params['project_id'];
        }
        $investigationModel->borrower = $data['borrowerState'];
        try {
            $investigationState = $investigationModel->save(false);
            if ($investigationState) {
                return true;
            }
            return false;
        } catch (\Exception $exception) {
            return false;
        }
    }


    /*
     *  保存/更新  *  保存/更新 预评估司法进展

     *  @$param $params 条件
     *  @$param $data   数据
     *  @return bool
     */
    public static function saveProjectPreEvaluationLawsuit($params, $data)
    {
        $update_state = false;   //flase 为新增，true为修改
        $userId = Yii::$app->user->id;
        $project_id = $params['project_id'];
        if (!empty($project_id)) {
            $lawsuitModel = ProjectPreEvaluationLawsuit::find()->where(['project_id' => $project_id])->one();
            $update_state = true;
        } else {
            $lawsuitModel = new ProjectPreEvaluationLawsuit();
        }
        if (empty($lawsuitModel)) {
            $lawsuitModel = new ProjectPreEvaluationLawsuit();
        }
        if (!empty($params['project_id'])) {
            $lawsuitModel->project_id = $params['project_id'];
        }
        $lawsuitModel->judgement = $data['judgement'];
        $lawsuitModel->execution = $data['execution'];
        $lawsuitModel->court = $data['court'];
        $lawsuitModel->block = $data['block'];
        $transaction = \Yii::$app->db->beginTransaction();
        $updateData = $lawsuitModel->getDirtyAttributes();

        $project = Project::findOne((int)$project_id);
        try {
            //更新
            if ($update_state) {
                ProjectPreEvaluationLawsuit::setUpdateLog($lawsuitModel->id, $lawsuitModel->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_JUDICIAL, $project->type, 2);
            }

            $lawsuitState = $lawsuitModel->save(false);
            if ($lawsuitState) {
                //新增
                if (!$update_state) {
                    ProjectPreEvaluationLawsuit::setUpdateLog($lawsuitModel->id, $lawsuitModel->project_id, $lawsuitModel, $userId, ProjectUpdateLog::MODULE_JUDICIAL, $project->type, 1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
    *  保存/更新  *  保存/更新 价值评估

    *  @$param $params 条件
    *  @$param $data   数据
    *  @return bool
    */
    public static function saveProjectEvaluation($params, $data)
    {
        $update_state = false;   //flase 为新增，true为修改
        $userId = Yii::$app->user->id;
        $project_id = $params['project_id'];
        if (!empty($project_id)) {
            $pingguModel = ProjectPreEvaluationValueEvaluation::find()->where(['project_id' => $project_id])->one();
            $update_state = true;
        } else {
            $pingguModel = new ProjectPreEvaluationValueEvaluation();
        }
        if (empty($pingguModel)) {
            $pingguModel = new ProjectPreEvaluationValueEvaluation();
        }
        if (!empty($params['project_id'])) {
            $pingguModel->project_id = $params['project_id'];
        }
        $pingguModel->reference = $data['reference'];
        $pingguModel->conservation = $data['conservation'];
        $pingguModel->radical = $data['radical'];
        $pingguModel->recall = $data['recall'];
        $transaction = \Yii::$app->db->beginTransaction();
        $updateData = $pingguModel->getDirtyAttributes();

        $project = Project::findOne((int)$project_id);
        try {
            //更新
            if ($update_state) {
                ProjectPreEvaluationValueEvaluation::setUpdateLog($pingguModel->id, $pingguModel->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_VALUE_RESERVATION, /*$project->type,*/
                    2);
            }
            $pingguState = $pingguModel->save(false);
            if ($pingguState) {
                //新增
                if (!$update_state) {
                    ProjectPreEvaluationValueEvaluation::setUpdateLog($pingguModel->id, $pingguModel->project_id, $pingguModel, $userId, ProjectUpdateLog::MODULE_VALUE_RESERVATION, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
       *  保存/更新  *  保存/更新 价值评估
       *  @$param $params 条件
       *  @$param $data   数据
       *  @return bool
       */
    public static function saveProjectOtherNote($params, $data)
    {
        $update_state = false;   //flase 为新增，true为修改
        $userId = Yii::$app->user->id;
        $project_id = $params['project_id'];
        if (!empty($project_id)) {
            $noteModel = ProjectPreEvaluationOtherNote::find()->where(['project_id' => $project_id])->one();
            $update_state = true;
        } else {
            $noteModel = new ProjectPreEvaluationOtherNote();
        }
        if (empty($noteModel)) {
            $noteModel = new ProjectPreEvaluationOtherNote();
        }
        if (!empty($params['project_id'])) {
            $noteModel->project_id = $params['project_id'];
        }
        $noteModel->legal = $data['legal'];
        $noteModel->sell_plan = $data['sell_plan'];
        $noteModel->risk_point = $data['risk_point'];
        $noteModel->current_state = $data['current_state'];
        $noteModel->other_problem = $data['other_problem'];
        $noteModel->more_problem = $data['more_problem'];
        $transaction = \Yii::$app->db->beginTransaction();
        $updateData = $noteModel->getDirtyAttributes();
        try {
            //更新
            if ($update_state) {
                ProjectPreEvaluationOtherNote::setUpdateLog($noteModel->id, $noteModel->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_ADDITIONAL_REMARKS, /*$project->type,*/
                    2);
            }
            $noteState = $noteModel->save(false);
            if ($noteState) {
                //新增
                if (!$update_state) {
                    ProjectPreEvaluationOtherNote::setUpdateLog($noteModel->id, $noteModel->project_id, $noteModel, $userId, ProjectUpdateLog::MODULE_ADDITIONAL_REMARKS, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }


    public static function saveProjectTransferHistory2($params, $data)
    {
        $userId = Yii::$app->user->id;
        $project_id = $params['project_id'];
        $instaerData = [];
        $updateData = [];

        foreach ($data as $k => $v) {
            $v['order'] = $k;
            $historyModel = ProjectTransferHistory::findOne((int)$v['historyId']);
            if ($historyModel !== null && $historyModel->project_id == $project_id) {
                $updateData[] = $v;
            } else {
                $instaerData[] = $v;
            }
        }

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //$insert_state = false;
            //$update_state = false;
            if (!empty($instaerData) && is_array($instaerData)) {
                foreach ($instaerData as $key => $value) {
                    $projectTransferHistory = new ProjectTransferHistory();
                    $projectTransferHistory->project_id = $project_id;
                    $projectTransferHistory->transfer_date = isset($value['transfer_date']) ? $value['transfer_date'] : '';
                    $projectTransferHistory->transfer = isset($value['transfer']) ? $value['transfer'] : '';
                    $projectTransferHistory->content = isset($value['content']) ? $value['content'] : '';
                    $projectTransferHistory->remark = isset($value['remark']) ? $value['remark'] : '';
                    $projectTransferHistory->order = isset($value['order']) ? (int)$value['order'] : 0;
                    $projectTransferHistory->lock_user = null;
                    $projectTransferHistory->lock_timestamp = null;
                    $insert_res = $projectTransferHistory->save(false);
                    if ($insert_res) {
                        //TODO 记录
                        ProjectTransferHistory::setUpdateLog($projectTransferHistory->id, $project_id, $projectTransferHistory, $userId, ProjectUpdateLog::MODULE_CONVERSION, 1);
                    } else {
                        $error = $projectTransferHistory->getFirstErrors();
                        $msg = '';
                        foreach ($error as $val) {
                            $msg .= $val;
                        }
                        throw new Exception($error);
                    }
                }
            }

            if (!empty($updateData) && is_array($updateData)) {
                foreach ($updateData as $key => $attributes) {
                    $projectTransferHistory = ProjectTransferHistory::findOne((int)$attributes['historyId']);
                    unset($attributes['historyId']);
                    if ($projectTransferHistory !== null) {
                        $attributes['project_id'] = $project_id;
                        $changedAttributes = array();

                        if ($projectTransferHistory->transfer_date != $attributes['transfer_date']) {
                            $projectTransferHistory->transfer_date = $attributes['transfer_date'];
                            $changedAttributes['transfer_date'] = $attributes['transfer_date'];
                        }

                        if ($projectTransferHistory->transfer != $attributes['transfer']) {
                            $projectTransferHistory->transfer = $attributes['transfer'];
                            $changedAttributes['transfer'] = $attributes['transfer'];
                        }

                        if ($projectTransferHistory->content != $attributes['content']) {
                            $projectTransferHistory->content = $attributes['content'];
                            $changedAttributes['content'] = $attributes['content'];
                        }

                        if ($projectTransferHistory->remark != $attributes['remark']) {
                            $projectTransferHistory->remark = $attributes['remark'];
                            $changedAttributes['remark'] = $attributes['remark'];
                        }

                        if ($projectTransferHistory->order != $attributes['order']) {
                            $projectTransferHistory->order = $attributes['order'];
                            $changedAttributes['order'] = $attributes['order'];
                        }

                        //TODO 记录
                        if (!empty($changedAttributes)) {
                            ProjectTransferHistory::setUpdateLog($projectTransferHistory->id, $project_id, $changedAttributes, $userId, ProjectUpdateLog::MODULE_CONVERSION, 2);
                        }
                        $update_res = $projectTransferHistory->save(false);
                        if (!$update_res) {
                            $error = $projectTransferHistory->getFirstErrors();
                            $msg = '';
                            foreach ($error as $value) {
                                $msg .= $value;
                            }
                            throw new Exception($error);
                        }
                    }
                }
            }

            $transaction->commit();
            return array('code' => 200, 'msg' => '保存成功');
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $transaction->rollBack();
            return array('code' => 400, 'msg' => $msg);
        } catch (\Throwable $e) {
            $msg = $e->getMessage();
            $transaction->rollBack();
            return array('code' => 400, 'msg' => $msg);
        }
    }

    /*
     *  保存/更新  *  保存/更新 流转记录
     *  @$param $params 条件
     *  @$param $data   数据
     *  @return bool
     */
    public static function saveProjectTransferHistory($params, $data)
    {
        $project_id = $params['project_id'];
        $updateData = [];
        $instaerData = [];
        foreach ($data as $k => $v) {
            $historyModel = ProjectTransferHistory::find()->where(['id' => $v['historyId']])->all();
            if (empty($historyModel)) {
                unset($v['historyId']);
                $instaerData[] = $v;
            } else {
                $updateData[] = $v;
            }
        }

        //再执行批量插入
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if (!empty($instaerData)) {
                $plankey = ['project_id', 'transfer_date', 'transfer', 'content', 'remark', 'order'];
                $instaerState = Yii::$app->db->createCommand()
                    ->batchInsert(ProjectTransferHistory::tableName(), $plankey, $instaerData)->execute();
            } else {
                $instaerState = 1;
            }

            if (!empty($updateData)) {
                for ($i = 0; $i < count($updateData); $i++) {
                    $id = $updateData[$i]['historyId'];
                    $updateState = Yii::$app->db->createCommand()
                        ->update(ProjectTransferHistory::tableName(), [
                            'transfer_date' => $updateData[$i]['transfer_date'],
                            'transfer' => $updateData[$i]['transfer'],
                            'content' => $updateData[$i]['content'],
                            'remark' => $updateData[$i]['remark'],
                            'order' => $updateData[$i]['order']
                        ], "id = $id")
                        ->execute();
                }
            } else {
                $updateState = 1;
            }
            $transaction->commit();
            return Responses::response200([$instaerData, $updateData], 1, "保存成功");
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
 *  删除 流转记录
 *  @$param $params 条件
 *  @return bool
 */
    public static function delProjectTransferHistory($params)
    {
        $project_id = $params['project_id'];
        $id = $params['id'];
        $delState = false;
        if (!empty($project_id) && !empty($id)) {
            $delData = ProjectTransferHistory::find()->where(['project_id' => $project_id])->andWhere(['id' => $id])->one();
        }
        if (!empty($delData)) {
            //TODO 记录
            ProjectTransferHistory::setUpdateLog($id, $project_id, array(), Yii::$app->user->id, ProjectUpdateLog::MODULE_CONVERSION, 3);

            $delState = $delData->delete();
        }
        if ($delState) {
            return true;
        }
        return false;
    }

    /*
*  删除 抵押物基础信息
*  @$param $params 条件
*  @return bool
*/
    public static function delMortgageProject($params)
    {
        $project_id = $params['project_id'];
        $mortgage_id = $params['mortgage_id'];
        $ppes_id = $params['ppes_id'];
        $delState = false;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if (!empty($project_id) && !empty($mortgage_id)) {
                $delData = ProjectPreEvaluationSeal::find()->where(['id' => $ppes_id])->andWhere(['mortgage_id' => $mortgage_id])->one();
            }
            //删除 project_pre_evaluation_seal 表数据
            if (!empty($delData)) {
                $delState = $delData->delete();
                $mortgageInfoData = ProjectPreEvaluationSeal::find()->andWhere(['mortgage_id' => $mortgage_id])->all();
            }
            //如果 project_pre_evaluation_seal 中还有数据则不删除 project_pre_evaluation_mortgage 数据删除
            if (empty($mortgageInfoData)) {
                $delMortgageBaseData = ProjectPreEvaluationMortgage::find()->where(['id' => $mortgage_id])->andWhere(['project_id' => $project_id])->one();
            }
            if (!empty($delMortgageBaseData)) {
                $delMortgageBaseState = $delMortgageBaseData->delete();
            } else {
                $delMortgageBaseState = true;
            }
            if ($delMortgageBaseState && $delState) {
                $transaction->commit();
                return Responses::response200([], 1, "保存成功");
            }
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
          *  保存/更新  *  保存/更新 转让信息
          *  @$param $params 条件
          *  @$param $data   数据
          *  @return bool
          */
    public static function saveProjectTransfer($params, $data)
    {
        $userId = Yii::$app->user->id;
        $update_state = false;
        $project_id = $params['project_id'];
        if (!empty($project_id)) {
            $transferModel = ProjectTransfer::find()->where(['project_id' => $project_id])->andWhere(['=', 'transfer', $data['transfer']])->one();
            $update_state = true;
        } else {
            $transferModel = new ProjectTransfer();
            $transferModel->project_id = $params['project_id'];
        }
        if (empty($transferModel)) {
            $transferModel = new ProjectTransfer();
            $transferModel->project_id = $params['project_id'];
        }
        $transferModel->transfer = $data['transfer'];
        $transferModel->contact = $data['contact'];
        $transferModel->phone = $data['phone'];
        $transferModel->email = $data['email'];
        $transferModel->address = $data['address'];
        $transferModel->position = $data['position'];
        $transferModel->method = $data['method'];
        $transferModel->wish = $data['wish'];
        $transferModel->expected_transfer = $data['expected_transfer'];
        $transferModel->detail = $data['detail'];
        $transferModel->remark = $data['remark'];
        $transaction = \Yii::$app->db->beginTransaction();
        $updateData = $transferModel->getDirtyAttributes();

        try {
            if ($update_state) {
                $transferModel->setUpdateLog($transferModel->id, $transferModel->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_TRANSFER/*, $module_type*/, 2);
            }

            $transferState = $transferModel->save(false);
            if ($data['state'] == 1) {
                $delState = self::delProjectTransfer($params);
            } else {
                $delState = true;
            }
            if ($transferState && $delState) {
                if (!$update_state) {
                    $transferModel->setUpdateLog($transferModel->id, $transferModel->project_id, $transferModel, $userId, ProjectUpdateLog::MODULE_TRANSFER/*, $module_type*/, 1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
     * 删除 转让信息 居中人
     *  @$param $params 条件
     *  @return bool
     */

    public static function delProjectTransfer($params)
    {
        $project_id = $params['project_id'];
        $transfer = 2;
        $delState = true;
        $delData = ProjectTransfer::find()->where(['project_id' => $project_id])->andWhere(['transfer' => $transfer])->one();
        if (!empty($delData)) {
            $delState = $delData->delete();
        }
        if ($delState) {
            return true;
        }
        return false;
    }

    /*
         *  保存/更新  *  保存/更新 团队
         *  @$param $params 条件
         *  @$param $data   数据
         *  @return bool
         */
    public static function saveProjectTeam($params, $data)
    {
        $project_id = $params['project_id'];
        if (!empty($project_id)) {
            $teamModel = ProjectTeam::find()->where(['project_id' => $project_id])->one();
        } else {
            $teamModel = new ProjectTeam();
        }
        if (empty($teamModel)) {
            $teamModel = new ProjectTeam();
        }
        $teamModel->project_id = $params['project_id'];
        $teamModel->manager = $data['manager'];
        $teamModel->owner = $data['owner'];
        $teamModel->partner = $data['partner'];
        $teamModel->explain = $data['explain'];
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $teamState = $teamModel->save();

            $projectLog = new ProjectLog();
            $projectLog->project_id = $teamModel->project_id;
            $projectLog->created_at = date('Y-m-d H:i:s');
            $projectLog->user_id = Yii::$app->user->id;
            $projectLog->log = "配置团队变更";
            $re = $projectLog->save();
            if (!$re) {
                //throw new Exception('单项目日志保存失败');
                $transaction->rollBack();
                return Responses::response400('单项目日志保存失败');
            }

            $userInfo = (new UserModel())->getDepartmentUsersList();
            $projectLog = new ProjectUpdateLog();
            $module_title_array = $projectLog->getModuleArrayTitle();
            $projectLog->project_id = $teamModel->project_id;
            $projectLog->created_at = date('Y-m-d H:i:s');
            $projectLog->type = is_null(Project::findOne($teamModel->project_id)->type) ? 1 : Project::findOne($teamModel->project_id)->type;
            $projectLog->user_id = Yii::$app->user->id;
            $projectLog->module = $module_title_array[ProjectUpdateLog::MODULE_PERMISSION];
            $manager_name = '';
            foreach (explode(",", $teamModel->manager) as $userId) {
                if ($userId != "" && $userId != "0")
                    $manager_name .= $value = $userInfo[$userId]['description'] . '—' . $userInfo[$userId]['realname'] . ';';
            }
            $projectLog->log = "项目总监更改为：" . $manager_name;
            $owner_name = '';
            foreach (explode(",", $teamModel->owner) as $userId) {
                if ($userId != "" && $userId != "0")
                    $owner_name .= $value = $userInfo[$userId]['description'] . '—' . $userInfo[$userId]['realname'] . ';';
            }
            $projectLog->log .= "项目经理更改为：" . $owner_name;
            $partner_name = '';
            foreach (explode(",", $teamModel->partner) as $userId) {
                if ($userId != "" && $userId != "0")
                    $partner_name .= $value = $userInfo[$userId]['description'] . '—' . $userInfo[$userId]['realname'] . ';';
            }
            $projectLog->log .= "团队成员更改为：" . $partner_name;
            $projectLog->log .= "其他说明更改为：" . $teamModel->explain;
            $re = $projectLog->save();
            if (!$re) {
                //throw new Exception('单项目日志保存失败');
                $transaction->rollBack();
                return Responses::response400('单项目日志保存失败');
            }
            if ($teamState) {
                $transaction->commit();
                return Responses::response200([], 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败' . $exception->getMessage());
        }
    }

    /*
     *查看单项目信息混合类信息
     */
    public static function getProjectInfoData($params)
    {
        $projectId = !empty($params['Id']) ? $params['Id'] : 1;
        $packageId = !empty($params['package_id']) ? $params['package_id'] : 1;
        $mortgageID = !empty($params['mortgage_id']) ? ['=', 'ppem.id', $params['mortgage_id']] : [];
        $ppeiID = !empty($params['ppesid']) ? ['=', 'ppei.ppes_id', $params['ppesid']] : [];
        $ppevID = !empty($params['ppesid']) ? ['=', 'ppev.ppes', $params['ppesid']] : [];
        $ppesID = !empty($params['ppesid']) ? ['=', 'ppes.id', $params['ppesid']] : [];
        if (!empty($projectId)) {
            $projectInfoData['Base'] = (new \yii\db\Query())->from(Project::tableName())->where(['=', 'id', $projectId])->one();
            $projectInfoData['Base']['provinceName'] = (new \yii\db\Query())->from('country')->where(['=', 'id', $projectInfoData['Base']['province']])->one()['title'];
            $projectInfoData['Base']['cityName'] = (new \yii\db\Query())->from('country')->where(['=', 'id', $projectInfoData['Base']['city']])->one()['title'];
            $projectInfoData['Base']['borrowerStatus'] = (new \yii\db\Query())->from('project_investigation_stakeholder')->where(['=', 'project_id', $projectInfoData['Base']['id']])->one()['borrower'];
            $projectInfoData['Lawsuit'] = (new \yii\db\Query())->from(ProjectPreEvaluationLawsuit::tableName())->where(['=', 'project_id', $projectId])->one();
            $projectInfoData['evaluation'] = (new \yii\db\Query())->from(ProjectPreEvaluationValueEvaluation::tableName())->where(['=', 'project_id', $projectId])->one();
            $projectInfoData['transfer']['chi'] = (new \yii\db\Query())->from(ProjectTransfer::tableName())->where(['=', 'project_id', $projectId])->andWhere(['=', 'transfer', 1])->one();
            $projectInfoData['transfer']['ju'] = (new \yii\db\Query())->from(ProjectTransfer::tableName())->where(['=', 'project_id', $projectId])->andWhere(['=', 'transfer', 2])->one();
            //如果项目没有数据，则从资产包的转发让表查找
            if (empty($projectInfoData['transfer']['chi']) && empty($projectInfoData['transfer']['ju'])) {
                $projectInfoData['transfer']['chi'] = (new \yii\db\Query())->from(PackageTransfer::tableName())->where(['=', 'package_id', $packageId])->andWhere(['=', 'transfer', 1])->one();
                $projectInfoData['transfer']['ju'] = (new \yii\db\Query())->from(PackageTransfer::tableName())->where(['=', 'package_id', $packageId])->andWhere(['=', 'transfer', 2])->one();
            }
            $projectInfoData['transferHistory'] = (new \yii\db\Query())->from(ProjectTransferHistory::tableName())->where(['=', 'project_id', $projectId])->all();
            //如果项目没有数据，则从资产包的转发让表查找
            if (empty($projectInfoData['transferHistory'])) {
                $projectInfoData['transferHistory'] = (new \yii\db\Query())->from(PackageTransferHistory::tableName())->where(['=', 'package_id', $packageId])->all();
            }
            $projectInfoData['team'] = (new \yii\db\Query())->from(ProjectTeam::tableName())->select('*')->where(['=', 'project_id', $projectId])->one();
            if (!empty($projectInfoData['team'])) {
                //通过id获取总监名称
                $leaderIdArr = [];
                if (!empty($projectInfoData['team']['manager']) && preg_match('/,/', $projectInfoData['team']['manager'])) {
                    $leaderIdArr = array_unique(explode(',', $projectInfoData['team']['manager']));
                } else if (is_string($projectInfoData['team']['manager'])) {
                    $leaderIdArr = $projectInfoData['team']['manager'];
                }
                $leader_name = (new \yii\db\Query())->select('user.id,user.realname,user.department,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['in', 'id', $leaderIdArr])->all();
                $projectInfoData['teamZJ'] = PackageInitiationPlan::pieceUsername($leader_name);
                //通过id获取负责人名称
                $ownerIdArr = [];
                if (!empty($projectInfoData['team']['owner']) && preg_match('/,/', $projectInfoData['team']['owner'])) {
                    $ownerIdArr = array_unique(explode(',', $projectInfoData['team']['owner']));
                } else if (is_string($projectInfoData['team']['owner'])) {
                    $ownerIdArr = $projectInfoData['team']['owner'];
                }
                $owner_name = (new \yii\db\Query())->select('id,realname,department,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['in', 'id', $ownerIdArr])->all();
                $projectInfoData['teamFZR'] = PackageInitiationPlan::pieceUsername($owner_name);
                //通过id获取协助人
                $partnerIdArr = [];
                if (!empty($projectInfoData['team']['partner']) && preg_match('/,/', $projectInfoData['team']['partner'])) {
                    $partnerIdArr = array_unique(explode(',', $projectInfoData['team']['partner']));
                } else if (is_string($projectInfoData['team']['partner'])) {
                    $partnerIdArr = $projectInfoData['team']['partner'];
                }
                $partner_name = (new \yii\db\Query())->select('id,realname,department,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['in', 'id', $partnerIdArr])->all();
                $projectInfoData['teamXZR'] = PackageInitiationPlan::pieceUsername($partner_name);
            } else {
                $projectInfoData['teamZJ'] = [];
                $projectInfoData['teamFZR'] = [];
                $projectInfoData['teamXZR'] = [];
            }
            //如果项目没有数据，则从资产包的转发让表查找
//            if (empty($projectInfoData['team'])){
//                $projectInfoData['team'] = (new \yii\db\Query())->from(PackageInitiationPlan::tableName())->where(['=', 'package_id', $packageId])->all();
//            }
            //获取所有用户名称
            $projectInfoData['user'] = (new \yii\db\Query())->select('*')->from(User::tableName())->all();
            $projectInfoData['userChief'] = (new \yii\db\Query())->select('*')->from(User::tableName())->andWhere(['=', 'is_leader', 1])->all();
//            $projectInfoData['history'] = (new \yii\db\Query())->from(PackageTransfer::tableName())->where(['=', 'project_id', $projectId])->all();
            $projectInfoData['note'] = (new \yii\db\Query())->from(ProjectPreEvaluationOtherNote::tableName())->where(['=', 'project_id', $projectId])->one();

            //非抵押物情况
//            $projectInfoData['nonMortgage'] = (new \yii\db\Query())->select('ppeov.bought_analysis,ppeov.bought_reservation,ppeov.bought_radical,ppeov.mortgage_other_seal_order,ppeov.mortgage_other_seal_state')->from("project as p")->leftJoin('project_pre_evaluation_mortgage as ppem', 'p.id = ppem.project_id')->leftJoin("project_pre_evaluation_other_value as ppeov", 'ppem.id = ppeov.mortgage_id')->leftJoin("project_pre_evaluation_seal as ppes", 'ppem.id = ppes.mortgage_id')->where(['=', 'p.id', $projectId])->one();
            $projectInfoData['nonMortgage'] = (new \yii\db\Query())->from("project_pre_evaluation_other_value")->where(['=', 'project_id', $projectId])->one();

            //回现评估
//            $projectInfoData['payment'] = (new \yii\db\Query())->select('ppc.payment_reservation,ppc.payment_radical,ppc.payment_tax,ppc.payment_month,ppc.payment_analysis')->from("project as p")->leftJoin('project_pre_evaluation_mortgage as ppem', 'p.id = ppem.project_id')->leftJoin("project_payment_collection as ppc", 'ppc.mortgage_id = ppem.id')->where(['=', 'p.id', $projectId])->one();
            $projectInfoData['payment'] = (new \yii\db\Query())->from("project_payment_collection")->where(['=', 'project_id', $projectId])->one();

            //抵押物情况
            $projectInfoData['mortgageCount'] = (new \yii\db\Query())->from('project_pre_evaluation_mortgage as ppem')->where(['=', 'ppem.project_id', $projectId])->count('*');
            //$projectInfoData['mortgageGroupMortgageId'] = (new \yii\db\Query())->select('ppes.mortgage_id')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_seal as ppes", 'ppes.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->groupBy('ppes.mortgage_id')->all();
            $projectInfoData['mortgageGroupMortgageId'] = (new \yii\db\Query())->select('ppem.id as mortgage_id')->from('project_pre_evaluation_mortgage as ppem')->where(['=', 'ppem.project_id', $projectId])->all();
            $projectInfoData['mortgageStateList'] = [];
            if (!empty($projectInfoData['mortgageGroupMortgageId']) && is_array($projectInfoData['mortgageGroupMortgageId'])) {
                foreach ($projectInfoData['mortgageGroupMortgageId'] as $k => $v) {
                    $projectInfoData['mortgageStateList'][$v['mortgage_id']] = (new \yii\db\Query())->select('*,ppem.id,ppes.id as ppesid')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_seal as ppes", 'ppes.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->andWhere(['=', 'ppem.id', $v['mortgage_id']])->orderBy('mortgage_order')->all();
                }
            }
            //1.抵押物信息
            $projectInfoData['mortgageInfoTable'] = (new \yii\db\Query())->select('ppem.id,ppes.mortgage_type,ppes.mortgage_owner,ppes.mortgage_code,ppes.mortgage_district,ppes.mortgage_address,ppes.mortgage_building_area,ppes.mortgage_land_area,ppes.maximum_mortgage,ppes.remaining_service_life')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_seal as ppes", 'ppes.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->andWhere($mortgageID)->andWhere($ppesID)->one();
            //2.抵押情况
            $projectInfoData['mortgageStateTable'] = (new \yii\db\Query())->select('*,ppem.id')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_seal as ppes", 'ppes.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->andWhere($mortgageID)->andWhere($ppesID)->one();
            //3.查封情况
            $projectInfoData['SealStateTable'] = (new \yii\db\Query())->select('*,ppem.id')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_seal as ppes", 'ppes.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->andWhere($mortgageID)->andWhere($ppesID)->one();
            //4.现场访谈
            $projectInfoData['InterviewTable'] = (new \yii\db\Query())->select('*,ppem.id')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_interview as ppei", 'ppei.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->andWhere($mortgageID)->andWhere($ppeiID)->one();
            //5.定价评估
            $projectInfoData['EvaluationTable'] = (new \yii\db\Query())->select('*,ppem.id')->from('project_pre_evaluation_mortgage as ppem')->leftJoin("project_pre_evaluation_value as ppev", 'ppev.mortgage_id = ppem.id')->where(['=', 'ppem.project_id', $projectId])->andWhere($mortgageID)->andWhere($ppevID)->one();
//            //判断是否费亮点项目
//            if ($projectInfoData['Base']['is_highlights']==1){
//
//            }else{
//
//            }
            return Responses::response200($projectInfoData);
        }
    }

    /*
     * 获取所有成员的信息
     */
    public static function getTeamUserData($id)
    {
        $query = (new \yii\db\Query())
            ->select('*')
            ->from('user u')
            ->where(['id' => $id])
            ->all();
        return $query;
    }

    /*
          *  保存/更新  *  保存/更新 非抵押物情况
          *  @$param $params 条件
          *  @$param $data   数据
          *  @return bool
          */
    public static function saveProjectNonMortgage($params, $data)
    {
        $project_id = $params['project_id'];
        $evaluationOtherValState = self::saveEvaluationOtherValData($project_id, $data);
        if ($evaluationOtherValState['code'] == 200) {
            return Responses::response200($evaluationOtherValState['data']['res'], 1, "保存成功");
        } else {
            return Responses::response400('提交失败');
        }
        /*//1.查看抵押物表是否有数据
        if (!empty($project_id)) {
            $mortgageModel = ProjectPreEvaluationMortgage::find()->where(['project_id' => $project_id])->one();
        } else {
            $mortgageModel = new ProjectPreEvaluationMortgage();
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //2.获取抵押表的id
            if (empty($mortgageModel)) {
                $mortgageModel = new ProjectPreEvaluationMortgage();
                $mortgageModel->project_id = $params['project_id'];
                $mortgageState = $mortgageModel->save(false);
                $mortgageId = Yii::$app->db->getLastInsertID();
            } else {
                $mortgageId = $mortgageModel['id'];
                $mortgageState = true;
            }
//            $evaluationSealState = self::saveEvaluationSealData($mortgageId, $data);
            $evaluationOtherValState = self::saveEvaluationOtherValData($mortgageId, $data);
            if ($mortgageState && $evaluationOtherValState['code'] == 200) {
                $transaction->commit();
                return Responses::response200($evaluationOtherValState['data']['res'], 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }*/
    }

    /*
     * 保存 (抵押类项目预评估)抵押查封
        $mortgageId:抵押表id
        $data:保存的数据
    */
    public static function saveEvaluationSealData($mortgageId, $data)
    {
        //1.查看抵押物表是否有数据
        if (!empty($mortgageId)) {
            $mortgageModel = ProjectPreEvaluationSeal::find()->where(['mortgage_id' => $mortgageId])->one();
        } else {
            $mortgageModel = new ProjectPreEvaluationSeal();
            $mortgageModel->mortgage_id = $mortgageId;
        }
        if (empty($mortgageModel)) {
            $mortgageModel = new ProjectPreEvaluationSeal();
            $mortgageModel->mortgage_id = $mortgageId;
        }
        $mortgageModel->mortgage_other_seal_order = $data['mortgage_other_seal_order'];
        $mortgageModel->mortgage_other_seal_state = $data['mortgage_other_seal_state'];
        try {
            $mortgageSate = $mortgageModel->save();
            if ($mortgageSate) {
                return true;
            }
            return false;
        } catch (\Exception $exception) {
            return false;
        }
    }

    /*
     * 保存 (非抵押物价值评估
        $mortgageId:抵押表id
        $data:保存的数据
    */
    public static function saveEvaluationOtherValData($projectId, $data)
    {
        //1.查看抵押物表是否有数据
        if (!empty($projectId)) {
            $mortgageModel = ProjectPreEvaluationOtherValue::find()->where(['project_id' => $projectId])->one();
        } else {
            $mortgageModel = new ProjectPreEvaluationOtherValue();
            $mortgageModel->project_id = $projectId;
        }
        if (empty($mortgageModel)) {
            $mortgageModel = new ProjectPreEvaluationOtherValue();
            $mortgageModel->project_id = $projectId;
        }
        $mortgageModel->project_id = $data['Id'];
        $mortgageModel->bought_analysis = $data['bought_analysis'];
        $mortgageModel->bought_reservation = $data['bought_reservation'];
        $mortgageModel->bought_radical = $data['bought_radical'];
        $mortgageModel->mortgage_other_seal_state = $data['mortgage_other_seal_state'];
        $mortgageModel->mortgage_other_seal_order = $data['mortgage_other_seal_order'];
        $updateData = $mortgageModel->getDirtyAttributes();
        $mortgageSate = $mortgageModel->save(false);
        if ($mortgageSate) {
            return Responses::response200($updateData);
        } else {
            return false;
        }
//        try {
//            $mortgageSate = $mortgageModel->save(false);
//            if ($mortgageSate) {
//                return Responses::response200($updateData);
//            }
//            return false;
//        } catch (\Exception $exception) {
//            return false;
//        }
    }

    /*
       *  保存/更新  *  保存/更新 非抵押物情况
       *  @$param $params 条件
       *  @$param $data   数据
       *  @return bool
       */
    public static function saveProjectMortgageData($params, $data)
    {
        $project_id = $params['project_id'];
        //1.查看抵押物表是否有数据
        if (!empty($project_id)) {
            $mortgageModel = ProjectPreEvaluationMortgage::find()->where(['project_id' => $project_id])->one();
        } else {
            $mortgageModel = new ProjectPreEvaluationMortgage();
        }

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //2.获取抵押表的id
            if (empty($mortgageModel)) {
                $mortgageModel = new ProjectPreEvaluationMortgage();
                $mortgageModel->project_id = $params['project_id'];
                $mortgageModel->mortgage_interest = $data['mortgage_interest'];
                $mortgageModel->mortgage_principal = $data['mortgage_principal'];
                $mortgageState = $mortgageModel->save(false);
                $mortgageId = Yii::$app->db->getLastInsertID();
            } else {
                $mortgageId = $mortgageModel['id'];
                $mortgageState = true;
            }
            $mortgageInfoState = self::saveMortgageInfo($mortgageId, $data);
            if ($mortgageState && $mortgageInfoState) {
                $transaction->commit();
                return Responses::response200([], 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
         * 保存 抵押类抵押物情况
            $mortgageId:抵押表id
            $data:保存的数据
        */
    public function saveMortgageInfo($mortgageId, $data)
    {
        //1.查看抵押物表是否有数据
        if (!empty($mortgageId)) {
            $evaluationModel = ProjectPreEvaluationSeal::find()->where(['mortgage_id' => $mortgageId])->one();
        } else {
            $evaluationModel = new ProjectPreEvaluationSeal();
            $evaluationModel->mortgage_id = $mortgageId;
        }
        if (empty($evaluationModel)) {
            $evaluationModel = new ProjectPreEvaluationSeal();
            $evaluationModel->mortgage_id = $mortgageId;
        }
        $evaluationModel->mortgage_owner = $data['mortgage_owner'];
        $evaluationModel->mortgage_type = $data['mortgage_type'];
        $evaluationModel->mortgage_code = $data['mortgage_code'];
        try {
            $evaluationSate = $evaluationModel->save(false);
            if ($evaluationSate) {
                return true;
            }
            return false;
        } catch (\Exception $exception) {
            return false;
        }
    }

    /*
   *  保存/更新  *  保存/更新 非抵押物情况
   *  @$param $params 条件
   *  @$param $data   数据
   *  @return bool
   */
    public static function saveProjectPayment($params, $data)
    {
        $project_id = $params['project_id'];
        $mortgageInfoState = self::savePaymentData($project_id, $data);
        if ($mortgageInfoState['code'] == 200) {
            return Responses::response200($mortgageInfoState['data']['res'], 1, "保存成功");
        } else {
            return Responses::response400('提交失败');
        }
        /*  //1.查看抵押物表是否有数据
          if (!empty($project_id)) {
              $mortgageModel = ProjectPreEvaluationMortgage::find()->where(['project_id' => $project_id])->one();
          } else {
              $mortgageModel = new ProjectPreEvaluationMortgage();
          }

          $transaction = \Yii::$app->db->beginTransaction();
          try {
              //2.获取抵押表的id
              if (empty($mortgageModel)) {
                  $mortgageModel = new ProjectPreEvaluationMortgage();
                  $mortgageModel->project_id = $params['project_id'];
                  $mortgageState = $mortgageModel->save(false);
                  $mortgageId = Yii::$app->db->getLastInsertID();
              } else {
                  $mortgageId = $mortgageModel['id'];
                  $mortgageState = true;
              }
              $mortgageInfoState = self::savePaymentData($mortgageId, $data);
              if ($mortgageState && $mortgageInfoState['code'] == 200) {
                  $transaction->commit();
                  return Responses::response200($mortgageInfoState['data']['res'], 1, "保存成功");
              }
              $transaction->rollBack();
              return Responses::response400('提交失败');
          } catch (\Exception $exception) {
              $transaction->rollBack();
              return Responses::response400('提交失败');
          }*/
    }

    /*
     * 保存 (（抵押类项目预评估）回现评估
        $mortgageId:抵押表id
        $data:保存的数据
    */
    public static function savePaymentData($projectId, $data)
    {
        //1.查看抵押物表是否有数据
        if (!empty($projectId)) {
            $paymentModel = ProjectPaymentCollection::find()->where(['project_id' => $projectId])->one();
        } else {
            $paymentModel = new ProjectPaymentCollection();
            $paymentModel->project_id = $projectId;
        }
        if (empty($paymentModel)) {
            $paymentModel = new ProjectPaymentCollection();
            $paymentModel->project_id = $projectId;
        }
        $paymentModel->project_id = $data['Id'];
        $paymentModel->payment_reservation = $data['payment_reservation'];
        $paymentModel->payment_radical = $data['payment_radical'];
        $paymentModel->payment_tax = $data['payment_tax'];
        $paymentModel->payment_month = $data['payment_month'];
        $paymentModel->payment_analysis = $data['payment_analysis'];
        $updateData = $paymentModel->getDirtyAttributes();
        $paymentSate = $paymentModel->save(false);
        if ($paymentSate) {
            return Responses::response200($updateData);
        }
        return false;

    }

    /*
       *  保存/更新  1.抵押物信息
       *  @$param $params 条件
       *  @$param $data   数据
       *  @return bool
       */
    public static function SaveMortgageInfoTable($params, $data)
    {
        $userId = Yii::$app->user->id;
        $update_state = false;
        $ppseid = $params['ppseid'];
        //1.查看抵押物表是否有数据
        if (!empty($ppseid)) {
            $evaluationSealModel = ProjectPreEvaluationSeal::find()->where(['id' => $ppseid])->one();
            $update_state = true;
        } else {
            $evaluationSealModel = new ProjectPreEvaluationSeal();
        }
        if (empty($evaluationSealModel)) {
            $evaluationSealModel = new ProjectPreEvaluationSeal();
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $evaluationSealModel->mortgage_id = $data['mortgage_id'];
            $evaluationSealModel->mortgage_type = $data['mortgage_type'];
            $evaluationSealModel->mortgage_owner = $data['mortgage_owner'];
            $evaluationSealModel->mortgage_code = $data['mortgage_code'];
            $evaluationSealModel->mortgage_district = $data['mortgage_district'];
            $evaluationSealModel->mortgage_address = $data['mortgage_address'];
            $evaluationSealModel->mortgage_building_area = $data['mortgage_building_area'];
            $evaluationSealModel->mortgage_land_area = $data['mortgage_land_area'];
            $evaluationSealModel->maximum_mortgage = $data['maximum_mortgage'];
            $evaluationSealModel->remaining_service_life = $data['remaining_service_life'];
            $updateData = $evaluationSealModel->getDirtyAttributes();
            $mortage = ProjectPreEvaluationMortgage::findOne($evaluationSealModel->mortgage_id);

            if ($update_state) {
                ProjectPreEvaluationSeal::setUpdateLog($evaluationSealModel->id, $mortage->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_PLEDGER_BASE, /*$project->type, */
                    2);
            }
            $evaluationSealState = $evaluationSealModel->save(false);
            if ($evaluationSealState) {
                if (!$update_state) {
                    $mortage = ProjectPreEvaluationMortgage::findOne($evaluationSealModel->mortgage_id);
                    ProjectPreEvaluationSeal::setUpdateLog($evaluationSealModel->id, $mortage->project_id, $evaluationSealModel, $userId, ProjectUpdateLog::MODULE_PLEDGER_BASE, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
      *  保存/更新  2.抵押情况
      *  @$param $params 条件
      *  @$param $data   数据
      *  @return bool
      */
    public static function SaveMortgageConditionTable($params, $data)
    {
        $userId = Yii::$app->user->id;
        $update_state = false;
        $ppseid = $params['ppseid'];
        //1.查看抵押物表是否有数据
        if (!empty($ppseid)) {
            $evaluationSealModel = ProjectPreEvaluationSeal::find()->where(['id' => $ppseid])->one();
        } else {
            $evaluationSealModel = new ProjectPreEvaluationSeal();
        }
        if (empty($evaluationSealModel)) {
            $evaluationSealModel = new ProjectPreEvaluationSeal();
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $evaluationSealModel->mortgage_id = $data['mortgage_id'];
            $evaluationSealModel->mortgage_order = $data['mortgage_order'];
            $evaluationSealModel->is_first_mortgage = $data['is_first_mortgage'];
            $evaluationSealModel->mortgage_future = $data['mortgage_future'];
            $evaluationSealModel->mortgage_situation = $data['mortgage_situation'];
            $updateData = $evaluationSealModel->getDirtyAttributes();
            $evaluationSealState = $evaluationSealModel->save(false);
            $mortage = ProjectPreEvaluationMortgage::findOne($evaluationSealModel->mortgage_id);

            if ($update_state) {
                ProjectPreEvaluationSeal::setUpdateLog($evaluationSealModel->id, $mortage->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_PLEDGER_SEIZE, /*$project->type, */
                    2);
            }
            if ($evaluationSealState) {
                if (!$update_state) {
                    $mortage = ProjectPreEvaluationMortgage::findOne($evaluationSealModel->mortgage_id);
                    ProjectPreEvaluationSeal::setUpdateLog($evaluationSealModel->id, $mortage->project_id, $evaluationSealModel, $userId, ProjectUpdateLog::MODULE_PLEDGER_SEIZE, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
    *  保存/更新  3.查封情况
    *  @$param $params 条件
    *  @$param $data   数据
    *  @return bool
    */
    public static function SaveMortgageSealTable($params, $data)
    {
        $userId = Yii::$app->user->id;
        $update_state = false;
        $ppseid = $params['ppseid'];
        //1.查看抵押物表是否有数据
        if (!empty($ppseid)) {
            $evaluationSealModel = ProjectPreEvaluationSeal::find()->where(['id' => $ppseid])->one();
            $update_state = true;
        } else {
            $evaluationSealModel = new ProjectPreEvaluationSeal();
            $evaluationSealModel->mortgage_id = $data['mortgage_id'];
        }
        if (empty($evaluationSealModel)) {
            $evaluationSealModel = new ProjectPreEvaluationSeal();
            $evaluationSealModel->mortgage_id = $data['mortgage_id'];
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $evaluationSealModel->mortgage_seal_order = $data['mortgage_seal_order'];
            $evaluationSealModel->is_first_seal = $data['is_first_seal'];
            $evaluationSealModel->whether_exploration = $data['whether_exploration'];
            $evaluationSealModel->mortgage_seal_state = $data['mortgage_seal_state'];
            $updateData = $evaluationSealModel->getDirtyAttributes();
            $mortage = ProjectPreEvaluationMortgage::findOne($evaluationSealModel->mortgage_id);

            if ($update_state) {
                ProjectPreEvaluationSeal::setUpdateLog($evaluationSealModel->id, $mortage->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_PLEDGER_SEIZE, /*$project->type, */
                    2);
            }
            $evaluationSealState = $evaluationSealModel->save(false);
            if ($evaluationSealState) {
                if (!$update_state) {
                    $mortage = ProjectPreEvaluationMortgage::findOne($evaluationSealModel->mortgage_id);
                    ProjectPreEvaluationSeal::setUpdateLog($evaluationSealModel->id, $mortage->project_id, $evaluationSealModel, $userId, ProjectUpdateLog::MODULE_PLEDGER_SEIZE, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
    *  保存/更新  4.现场访谈
    *  @$param $params 条件
    *  @$param $data   数据
    *  @return bool
    */
    public static function SaveMortgageInterviewTable($params, $data)
    {
        $userId = Yii::$app->user->id;
        $update_state = false;
        $ppseid = $params['ppesid'];
        //1.查看抵押物表是否有数据
        if (!empty($ppseid)) {
            $interviewSealModel = ProjectPreEvaluationInterview::find()->where(['ppes_id' => $ppseid])->one();
            $update_state = true;
        } else {
            $interviewSealModel = new ProjectPreEvaluationInterview();
        }
        if (empty($interviewSealModel)) {
            $interviewSealModel = new ProjectPreEvaluationInterview();
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $interviewSealModel->mortgage_id = $data['mortgage_id'];
            $interviewSealModel->building_title = $data['building_title'];
            $interviewSealModel->finished_date = $data['finished_date'];
            $interviewSealModel->total_floor = $data['total_floor'];
            $interviewSealModel->which_floor = $data['which_floor'];
            $interviewSealModel->surroundings = $data['surroundings'];
            $interviewSealModel->property = $data['property'];
            $interviewSealModel->whether_work = $data['whether_work'];
            $interviewSealModel->is_only = $data['is_only'];
            $interviewSealModel->willing = $data['willing'];
            $interviewSealModel->market_price = $data['market_price'];
            $interviewSealModel->market_rent_price = $data['market_rent_price'];
            $interviewSealModel->comparison_property1 = $data['comparison_property1'];
            $interviewSealModel->comparison_property2 = $data['comparison_property2'];
            $interviewSealModel->comparison_property3 = $data['comparison_property3'];
            $interviewSealModel->comparison_property4 = $data['comparison_property4'];
            $interviewSealModel->info_origin = $data['info_origin'];
            $interviewSealModel->contact = $data['contact'];
            $interviewSealModel->remark = $data['remark'];
            $interviewSealModel->ppes_id = $ppseid;
            $interviewSealModel->property_state = $data['property_state'];
            $interviewSealModel->lease_info = $data['lease_info'];
            //如果是抵押类 则保存
            if ($data['whether_work'] == \Yii::$app->params['whetherWork'][4]['val']) {
                $interviewSealModel->lease_info = $data['lease_info'];
            }
            $updateData = $interviewSealModel->getDirtyAttributes();
            $mortage = ProjectPreEvaluationMortgage::findOne($interviewSealModel->mortgage_id);

            if ($update_state) {
                ProjectPreEvaluationInterview::setUpdateLog($interviewSealModel->id, $mortage->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_PLEDGER_INTERVIEW, /*$project->type, */
                    2);
            }
            $interviewSealState = $interviewSealModel->save(false);
            if ($interviewSealState) {
                if (!$update_state) {
                    ProjectPreEvaluationInterview::setUpdateLog($interviewSealModel->id, $mortage->project_id, $interviewSealModel, $userId, ProjectUpdateLog::MODULE_PLEDGER_INTERVIEW, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            } else {
                $error = $interviewSealModel->getFirstErrors();
                $msg = '';
                foreach ($error as $value) {
                    $msg .= $value;
                }
                return Responses::response400($msg);
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
    *  保存/更新  5.定价评估
    *  @$param $params 条件
    *  @$param $data   数据
    *  @return bool
    */
    public static function SaveEvaluationValueTable($params, $data)
    {
        $userId = Yii::$app->user->id;
        $update_state = false;
        $ppseid = $params['ppesid'];
        //1.查看抵押物表是否有数据
        if (!empty($ppseid)) {
            $evaluationModel = ProjectPreEvaluationValue::find()->where(['ppes' => $ppseid])->one();
            $update_state = true;
        } else {
            $evaluationModel = new ProjectPreEvaluationValue();
        }
        if (empty($evaluationModel)) {
            $evaluationModel = new ProjectPreEvaluationValue();
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $evaluationModel->mortgage_id = $data['mortgage_id'];
            $evaluationModel->price_reason = $data['price_reason'];
            $evaluationModel->payment_radical = $data['payment_radical'];
            $evaluationModel->payment_reservation = $data['payment_reservation'];
            $evaluationModel->market_radical_total_price = $data['market_radical_total_price'];
            $evaluationModel->market_conservation_total_price = $data['market_conservation_total_price'];
            $evaluationModel->market_radical_price = $data['market_radical_price'];
            $evaluationModel->market_conserve_price = $data['market_conserve_price'];
            $evaluationModel->auction_price = $data['auction_price'];
            $evaluationModel->third_partner_value_other = $data['third_partner_value_other'];
            $evaluationModel->third_partner_value = $data['third_partner_value'];
            $evaluationModel->bank_value = $data['bank_value'];
            $evaluationModel->ppes = $ppseid;
            $updateData = $evaluationModel->getDirtyAttributes();
            $mortage = ProjectPreEvaluationMortgage::findOne($evaluationModel->mortgage_id);

            if ($update_state) {
                ProjectPreEvaluationValue::setUpdateLog($evaluationModel->id, $mortage->project_id, $updateData, $userId, ProjectUpdateLog::MODULE_PLEDGER_PRICING_RESERVATION, /*$project->type, */
                    2);
            }
            $evaluationState = $evaluationModel->save(false);
            if ($evaluationState) {
                if (!$update_state) {
                    ProjectPreEvaluationValue::setUpdateLog($evaluationModel->id, $mortage->project_id, $evaluationModel, $userId, ProjectUpdateLog::MODULE_PLEDGER_PRICING_RESERVATION, /*$project->type, */
                        1);
                }
                $transaction->commit();
                return Responses::response200($updateData, 1, "保存成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
   *  保存  保存抵押类基础信息
   *  @$param $params 条件
   *  @$param $data   数据
   *  @return bool
   */
    public static function saveMortgageBaseInfo($params, $data)
    {
        $saveState = 0; //循环记录是否更新成功
        $project_id = $params['project_id'];
        if (!empty($data)) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $evaluationSealModel = new ProjectPreEvaluationSeal();
                foreach ($data as $k => $v) {
                    if (empty($v['mortgage_id'])) {
                        $evaluationModel = new ProjectPreEvaluationMortgage();
                        $evaluationModel->project_id = $project_id;
                        $evaluationModel->mortgage_principal = $v['mortgage_principal'];
                        $evaluationModel->mortgage_interest = $v['mortgage_interest'];
                        $evaluationState = $evaluationModel->save(false);
                        $saveMortgageId = \Yii::$app->db->getLastInsertID();
                    } else {
                        $evaluationState = true;
                        $saveMortgageId = $v['mortgage_id'];
                    }
                    foreach ($v['mortgage_info'] as $k1 => $v1) {
                        $sealModel = clone $evaluationSealModel;
                        $sealModel->mortgage_id = $saveMortgageId;
                        $sealModel->mortgage_owner = $v1['mortgage_owner'];
                        $sealModel->mortgage_type = $v1['mortgage_type'];
                        $sealModel->mortgage_code = $v1['mortgage_code'];

//                    $sealModel->mortgage_code = $v1['mortgage_order'];
                        $sealState = $sealModel->save(false);
                        if ($evaluationState && $sealState) {
                            $saveState++;
                        } else {
                            $saveState = 0;
                        }
                    }
                }

                if ($saveState > 0) {
                    $transaction->commit();
                    return Responses::response200([], 1, "保存成功");
                }
                $transaction->rollBack();
                return Responses::response200([], 1, "保存成功");
            } catch (\Exception $exception) {
                $transaction->rollBack();
                return Responses::response400('提交失败');
            }
        } else {
            return Responses::response400('提交失败');
        }
    }

    /*
  *  更新  抵押类基础信息
  *  @$param $params 条件
  *  @$param $data   数据
  *  @return bool
  */
    public static function updateMortgageBaseInfo($params, $data)
    {
        $saveState = 0; //循环记录是否更新成功
        $project_id = $params['project_id'];
        if (!empty($data)) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                foreach ($data as $k => $v) {
                    $mortgage_id = $v['mortgage_id'];
                    $evaluationModel = ProjectPreEvaluationMortgage::find()->where(['project_id' => $project_id])->andWhere(['=', 'id', $mortgage_id])->one();
                    if (!empty($evaluationModel)) {
                        $evaluationModel->mortgage_interest = $v['mortgage_interest'];
                        $evaluationModel->mortgage_principal = $v['mortgage_principal'];
                        $evaluationState = $evaluationModel->save(false);
                        foreach ($v['mortgage_info'] as $k1 => $v1) {
                            $ppes_id = $v1['ppesid'];
                            $preEvaluationSealModel = ProjectPreEvaluationSeal::find()->where(['=', 'mortgage_id', $mortgage_id])->andWhere(['=', 'id', $ppes_id])->one();
                            $preEvaluationSealModel->mortgage_owner = $v1['mortgage_owner'];
                            $preEvaluationSealModel->mortgage_type = $v1['mortgage_type'];
                            $preEvaluationSealModel->mortgage_code = $v1['mortgage_code'];
//                        $preEvaluationSealModel->mortgage_code = $v1['mortgage_order'];
                            $preEvaluationSealState = $preEvaluationSealModel->save(false);
                            if ($evaluationState && $preEvaluationSealState) {
                                $saveState++;
                            } else {
                                $saveState = 0;
                            }
                        }
                    } else {
                        return Responses::response400('无数据');
                    }
                }

                if ($saveState > 0) {
                    $transaction->commit();
                    return Responses::response200([], 1, "保存成功");
                }
                $transaction->rollBack();
                return Responses::response200([], 1, "保存成功");
            } catch (\Exception $exception) {
                $transaction->rollBack();
                return Responses::response400('提交失败');
            }
        } else {
            return Responses::response400('提交失败');
        }
    }

    public static function updateLog(array $data)
    {
        $projectUpdateLogModel = new ProjectUpdateLog();
        $projectUpdateLogModel->project_id = $data['project_id'];
        $projectUpdateLogModel->module = $data['module'];
        $projectUpdateLogModel->type = $data['type'];
        $projectUpdateLogModel->user_id = $data['user_id'];
        $projectUpdateLogModel->log = $data['log'];
        $state = $projectUpdateLogModel->save(false);
        if ($state) {
            return Responses::response200();
        }
        return Responses::response400();
    }


    /**
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * @param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public static function setUpdateLog($project_id, $changedAttributes, $userId, $module, $module_type, $type)
    {
        $model = Project::findOne($project_id);
        $package = Package::findOne($model->package_id);
        if ($model === null || $package === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        //添加项目修改操作日志
        $users = new UserModel();
        $realname = $users->getRealname($userId);
        $userList = $users->getDepartmentUsersList();
        //省市
        $country_title = Country::getTitleList();

        $attributeLabels = (new Project())->attributeLabels();
        $intAttributeLabels = ['package_id', 'access', 'access_users', 'status', 'industry', 'type', 'province', 'city', 'mortgage_type',
            'management_status', 'is_highlights', 'guarantor_status', 'lock_user', 'is_suit', 'is_finished', 'enterprise', 'type2'];
        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        $key = strtolower($key);
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'access':
                                    $title = Yii::$app->params['access'];
                                    $value = $title[$value];
                                    break;
                                case 'access_users':
                                    $arr = explode(',', trim($value, ','));
                                    $str = '';
                                    foreach ($arr as $v) {
                                        $str .= $userList[(int)$v]['realname'] . '，';
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                case 'status':
                                    $title = $model->getStatusTitle();
                                    if ($value == 4 || $value == 5) {
                                        $value = $title[$value];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'industry':
                                    if (strlen(trim($value, ',')) > 0) {
                                        $title = Yii::$app->params['industrys'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            $str .= $title[(int)$v]['name'] . '，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'type':
                                    if ($value == 2) {
                                        $value = '抵押类';
                                    } else {
                                        $value = '混合类';
                                    }
                                    break;
                                case 'province':
                                    $value = $country_title[$value];
                                    break;
                                case 'city':
                                    $value = $country_title[$value];
                                    break;
                                case 'mortgage_type':
                                    if (strlen(trim($value, ',')) > 0) {
                                        $title = Yii::$app->params['mortgageTypes'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            $str .= $title[(int)$v]['name'] . '，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'management_status':
                                    $title = Yii::$app->params['managementStatus'];
                                    if ($value > 0) {
                                        $value = $title[(string)$value];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'is_highlights':
                                    $title = $model->getIsHighlightsTitle();
                                    $value = $title[$value];
                                    break;
                                case 'guarantor_status':
                                    $title = Yii::$app->params['guarantorStatus'];
                                    if ($value > 0) {
                                        $value = $title[(string)$value]['name'];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'enterprise':
                                    $title = Yii::$app->params['enterprises'];
                                    if ($value > 0) {
                                        $value = $title[(int)$value]['name'];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'lock_user':
                                    $value = $realname;
                                    break;
                                case  'is_suit':
                                    $title = $model->getIsSuitTitle();
                                    $value = $title[$value];
                                    break;
                                case 'is_finished':
                                    if ($value == 1) {
                                        $value = '已完成';
                                    } else {
                                        $value = '未完成';
                                    }
                                    break;
                                case 'type2':
                                    $title = Yii::$app->params['projectCategory'];
                                    if ($value > 0) {
                                        $value = $title[(int)$value]['name'];
                                    }
                                    break;
                                default:
                            }
                        }

                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    $key = strtolower($key);
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    return array('state' => true, 'msg' => '保存成功');
                    /*$model->lock_user = null;
                    $model->lock_timestamp = null;
                    if ($model->save()) {
                        return array('state' => true, 'msg' => '保存成功');
                    } else {
                        return array('state' => false, 'msg' => '保存失败');
                    }*/
                    //return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        $key = strtolower($key);
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'access':
                                    $title = Yii::$app->params['access'];
                                    $value = $title[$value];
                                    break;
                                case 'access_users':
                                    $arr = explode(',', trim($value, ','));
                                    $str = '';
                                    foreach ($arr as $v) {
                                        $str .= $userList[(int)$v]['realname'] . '，';
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                case 'status':
                                    $title = $model->getStatusTitle();
                                    if ($value == 4 || $value == 5) {
                                        $value = $title[$value];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'industry':
                                    if (strlen(trim($value, ',')) > 0) {
                                        $title = Yii::$app->params['industrys'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            $str .= $title[(int)$v]['name'] . '，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'type':
                                    if ($value == 2) {
                                        $value = '抵押类';
                                    } else {
                                        $value = '混合类';
                                    }
                                    break;
                                case 'province':
                                    $value = $country_title[$value];
                                    break;
                                case 'city':
                                    $value = $country_title[$value];
                                    break;
                                case 'mortgage_type':
                                    if (strlen(trim($value, ',')) > 0) {
                                        $title = Yii::$app->params['mortgageTypes'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            $str .= $title[(int)$v]['name'] . '，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'management_status':
                                    $title = Yii::$app->params['managementStatus'];
                                    if ($value > 0) {
                                        $value = $title[(string)$value];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'is_highlights':
                                    $title = $model->getIsHighlightsTitle();
                                    $value = $title[$value];
                                    break;
                                case 'guarantor_status':
                                    $title = Yii::$app->params['guarantorStatus'];
                                    if ($value > 0) {
                                        $value = $title[(string)$value]['name'];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'enterprise':
                                    $title = Yii::$app->params['enterprises'];
                                    if ($value > 0) {
                                        $value = $title[(int)$value]['name'];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'lock_user':
                                    $value = $realname;
                                    break;
                                case  'is_suit':
                                    $title = $model->getIsSuitTitle();
                                    $value = $title[$value];
                                    break;
                                case 'is_finished':
                                    if ($value == 1) {
                                        $value = '已完成';
                                    } else {
                                        $value = '未完成';
                                    }
                                    break;
                                case 'type2':
                                    $title = Yii::$app->params['projectCategory'];
                                    if ($value > 0) {
                                        $value = $title[(int)$value]['name'];
                                    }
                                    break;
                                default:
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            default:
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            $module_title_array = $projectUpdateLog->getModuleArrayTitle();
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            if ($module_type == 2) {
                $module_type = 2;
            } else {
                $module_type = 1;
            }
            $projectUpdateLog->type = $module_type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new Exception('更新记录添加失败');
            }

            return array('state' => true, 'msg' => '更新记录添加成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }
}
